﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace Solution
{
    public class ConfigHelper
    {
        /// <summary>
        /// 加载自定义的各种config,到字典集合【配合cache缓存实用】
        /// </summary>
        /// <param name="path">config路径</param>
        /// <param name="section">读取的节点（如：appSettings）</param>
        /// <returns></returns>
        public static IDictionary<string, string> GetKeyedConfigurationValues(string path, string section)
        {
            
            var map = new ExeConfigurationFileMap
            {
                ExeConfigFilename = HttpContext.Current.Server.MapPath(path)
            };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            var result = new Dictionary<string, string>();
            var settingsSection = configuration.GetSection(section) as AppSettingsSection;

            if (settingsSection != null)
            {
                foreach (KeyValueConfigurationElement setting in settingsSection.Settings)
                {
                    result.Add(setting.Key, setting.Value);
                }
            }

            return result;
        }


        /// <summary>
        /// 根据Key取Value值
        /// </summary>
        /// <param name="key"></param>
        public static string GetValue(string key)
        {
            return ConfigurationManager.AppSettings[key].ToString().Trim();
        }

        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        public static void SetValue(string key, string value)
        {
            ConfigurationManager.AppSettings.Set(key, value);
        }

        /// <summary>
        /// 添加新的Key ，Value键值对
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        public static void Add(string key, string value)
        {
            ConfigurationManager.AppSettings.Add(key, value);
        }

        /// <summary>
        /// 根据Key删除项
        /// </summary>
        /// <param name="key">Key</param>
        public static void Remove(string key)
        {
            ConfigurationManager.AppSettings.Remove(key);
        }
    }
}
